<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>修改业务分组</title>
    <link rel="stylesheet" href="../../../component/pear/css/pear.css"/>
    <link rel="stylesheet" href="../../../component/aieditor/style.css"/>
</head>
<body>
<form class="layui-form layui-form-pane" action="" name="frmMain">
    <input type="hidden" name="id" value="">
    <div class="mainBox">
        <div class="main-container">
            <div class="layui-form-item ">
                <label class="layui-form-label">分组名称</label>
                <div class="layui-input-block">
                    <input type="text" name="group_name" lay-verify="required" autocomplete="off"
                           placeholder="请输入字典名称"
                           class="layui-input">
                </div>
            </div>
            <div class="layui-form-item layui-form-text">
                <label class="layui-form-label">分组名称（填写业务说明）</label>
                <div class="layui-input-block" name="group_desc">
                    <input type="hidden" name="group_desc" value="">
                    <div id="group_desc_edit"></div>
                </div>
            </div>
        </div>
    </div>
    <div class="bottom">
        <div class="button-container">
            <button type="submit" class="pear-btn pear-btn-primary pear-btn-sm" lay-submit=""
                    lay-filter="user-save">
                <i class="layui-icon layui-icon-ok"></i>
                提交
            </button>
        </div>
    </div>
</form>
<script src="../../../config/apiUrl.js"></script>
<script src="../../../component/layui/layui.js"></script>
<script src="../../../component/pear/pear.js"></script>
<script type="module">
    import {AiEditor} from '../../../component/aieditor/index.js'

    layui.use(['form', 'jquery', 'http', 'popup', 'common', 'toast'], function () {
        let form = layui.form;
        let $ = layui.jquery;
        let http = layui.http;
        let popup = layui.popup;
        let common = layui.common;
        let toast = layui.toast;
        let id = common.getUrlParams("id");
        frmMain.id.value = id;
        function closeWin() {
            let layer_index = parent.layer.getFrameIndex(window.name);
            if (layer_index > 0) {
                parent.layer.close(layer_index); //关闭当前页
            }
        }

        $(document).keyup(function (event) {
            if (event.keyCode == 27) {
                closeWin();
            }
        });

        async function save(data){
            try {
                let return_data = await common.ajax({
                    url:apiUrlConfig.businessGroup.update,
                    data:JSON.stringify(data)
                })
                parent.layui.toast.success({title: false, message: '保存成功'})
                const bc = new BroadcastChannel('business_group_reload');
                bc.postMessage(data);
                closeWin();
            }catch (result){
                if (result.status == 10001) {
                    //字段提示
                    let errorMsg = JSON.parse(result.msg);
                    for (let key in errorMsg) {
                        layer.tips(errorMsg[key], $("[name='" + key + "']").parent(), {
                            tips: [3, '#f56c6c'], time: 5000, tipsMore: true
                        });
                    }
                }
            }
        }
        form.on('submit(user-save)', function (data) {
            layer.confirm('确定要保存业务分组吗？', {icon: 3, title: '提示'}, function (index) {
                layer.close(index);
                save(data.field);
            });
            return false;
        });

        async function getData() {
            let return_data = await common.ajax({
                url:apiUrlConfig.businessGroup.get+id,
                type:"get"
            })
            common.setForm(return_data.data,$("[name='frmMain']"));
            let group_desc_edit = new AiEditor({
                element: "#group_desc_edit",
                placeholder: "填写业务描述",
                content: return_data.data.group_desc,
                toolbarKeys: ["undo", "redo", "brush", "eraser",
                    "|", "heading", "font-family", "font-size",
                    "|", "bold", "italic", "underline", "strike", "link", "code", "subscript", "superscript", "hr", "todo", "emoji",
                    "|", "highlight", "font-color",
                    "|", "align", "line-height",
                    "|", "bullet-list", "ordered-list", "indent-decrease", "indent-increase", "break",
                    "|", "image", "quote", "code-block", "table",
                    "|", "printer", "fullscreen"
                ],
                onChange:(aiEditor)=>{
                    // 监听到用编辑器内容发生变化了，控制台打印编辑器的 html 内容...
                    frmMain.group_desc.value = aiEditor.getHtml();
                },
                image: {
                    allowBase64: false,
                    uploadUrl: apiUrlConfig.file.uploadFile,
                    uploadHeaders: {
                        "authorization": localStorage.getItem("token")
                    },
                    uploader: (file, uploadUrl, headers, formName) => {
                        //监听图片上传之前，此方法可以不用回任何内容，但若返回 false，则终止上传
                        const formData = new FormData();
                        formData.append("file", file);
                        return new Promise((resolve, reject) => {
                            fetch(uploadUrl, {
                                method: "post",
                                headers: {'Accept': 'application/json', ...headers},
                                body: formData,
                            }).then((resp) => resp.json())
                                .then(json => {
                                    resolve(json);
                                }).catch((error) => {
                                reject(error);
                            })
                        });
                    },
                    uploaderEvent: {
                        onUploadBefore: (file, uploadUrl, headers) => {
                            //监听图片上传之前，此方法可以不用回任何内容，但若返回 false，则终止上传
                        },
                        onSuccess: (file, response) => {
                            //监听图片上传成功
                            //注意：
                            // 1、如果此方法返回 false，则图片不会被插入到编辑器
                            // 2、可以在这里返回一个新的 json 给编辑器
                            if(response.status == 200){
                                let fileUrl = apiUrlConfig.file.getFile+"?token="+encodeURIComponent(localStorage.getItem("token"))+"&isOnLine=true&fileId="+response.data.id;
                                return {
                                    "errorCode": 0,
                                    "data": {
                                        "src": fileUrl,
                                        "alt": response.data.file_name
                                    }
                                }
                            }
                        },
                        onFailed: (file, response) => {
                            let toast = layui.toast;
                            toast.error({title: false, message: response.msg})
                        },
                        onError: (file, error) => {
                            let toast = layui.toast;
                            toast.error({title: false, message: error})
                        },
                    }
                }
            })
        }
        getData();

    })


</script>
</body>
</html>
